package entity

import (
	"fmt"
	"strconv"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//ShIndiLlcsdr 利率参数导入
type ShIndiLlcsdr struct {
	ID   int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	DBFS string    `gorm:"column:DBFS"`
	JE   string    `gorm:"column:JE"`
	QX   string    `gorm:"column:QX"`
	LL   float64   `gorm:"column:LL"`
	KVAL string    `gorm:"column:KVAL"`
	SXRQ time.Time `gorm:"column:SXRQ"`
}

//TableName
func (ShIndiLlcsdr) TableName() string {
	return "SH_INDI_LLCSDR"
}

// BeforeCreate
func (u *ShIndiLlcsdr) BeforeCreate(tx *gorm.DB) (err error) {
	var dbid, jeid, perd int
	err = base.CHDB.Raw("SELECT id FROM DICT_GUARANTEE WHERE name=?", u.DBFS).Row().Scan(&dbid)
	if err != nil {
		return err
	}
	if dbid == 0 {
		return fmt.Errorf("担保方式%s在系统中不存在！", u.DBFS)
	}
	if u.JE == "1000万元以下" {
		jeid = 1
	} else if u.JE == "1000万元以上" {
		jeid = 2
	} else {
		jeid = 3
	}
	if u.QX == "1年及以下" {
		perd = 1
	} else if u.QX == "1（不含）-3年（含）" {
		perd = 2
	} else if u.QX == "3（不含）-5年（含）" {
		perd = 3
	} else if u.QX == "5年以上" {
		perd = 4
	}
	u.KVAL = strconv.Itoa(dbid) + "_" + strconv.Itoa(jeid) + "_" + strconv.Itoa(perd)
	return
}
func ShIndiLlcsdrAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	sqlStr := "TRUNCATE TABLE JOIN_LLCSDR"
	err = base.CHDB.Exec(sqlStr).Error
	if err != nil {
		return err
	}
	sqlStr = `INSERT INTO JOIN_LLCSDR SELECT KVAL,LL FROM mysql.SH_INDI_LLCSDR WHERE SXRQ=?`
	var rq time.Time
	rq, err = time.Parse(time.RFC3339, params["SXRQ"])
	if err != nil {
		return err
	}
	pval := rq.Format("2006-01-02")
	err = base.CHDB.Exec(sqlStr, pval).Error
	if err != nil {
		return err
	}
	return
}

//ShIndiLlcsdrEF 返回结构体
func ShIndiLlcsdrEF() base.EntityFunc {
	return func() interface{} {
		entity := ShIndiLlcsdr{}
		return &entity
	}
}

//ShIndiLlcsdrESF 返回结构体数组
func ShIndiLlcsdrESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []ShIndiLlcsdr
		return &entities
	}
}

func init() {
	base.SetAfterCallBack("ShIndiLlcsdr", ShIndiLlcsdrAfterImport)
	base.DaoPoolObj.Put("ShIndiLlcsdr", base.NewDefaultDao(ShIndiLlcsdrEF(), ShIndiLlcsdrESF(), nil, "my"))
}
